package com.ea.controller;

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.IOException;

import java.util.Date;
import com.google.appengine.api.datastore.Text;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import java.util.List;

import com.ea.PMF;
import com.ea.model.Article;

public class ArticleServlet extends HttpServlet {

	public void doGet( HttpServletRequest request,
					HttpServletResponse response) throws IOException, ServletException	
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String s = request.getParameter("articleid");

		
		if( s == null ) // Get Last 5 Stories
		{	
			Query query = pm.newQuery(Article.class);
			query.setRange(0,8);
			query.setOrdering("date desc");
		    
			try{
				List<Article> results = (List<Article>) query.execute();
			
				request.setAttribute("articles",results);
				
				RequestDispatcher view = request.getRequestDispatcher("/jsp/Home.jsp");
				view.forward(request, response);
		
			}
			finally{
				pm.close();
			}
		}
		else // GET a PRECISE Article
		{
			Query query = pm.newQuery(Article.class, "key == " + s);
			query.setUnique(true);

			try{
				Article a = (Article) query.execute();
				request.setAttribute("article", a);
				RequestDispatcher view = request.getRequestDispatcher("/jsp/article.jsp");
				view.forward(request, response);
			}
			finally{
				pm.close();
			}			
		}	
	
	}// doGet		
	//---------------------------------------------------------------------------------------	
	public void doPost(HttpServletRequest request,
			HttpServletResponse response)throws IOException
	{
		Date d = new Date( request.getParameter("date"));
		Text t = new Text(request.getParameter("article"));
		
		Article a = new Article(
			d,	
			request.getParameter("title"),
			request.getParameter("keywords"),
			t
			);
	
		PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            pm.makePersistent(a);
        } finally {
            pm.close();
        }
		
	}// doPost
	
}
